'use strict';


const macaddress = require('macaddress');
const gql = require('graphql-tag');
const common = require('../common');
const licenseKey = require('license-key-gen');
const moment = require('moment');
const Service = require('egg').Service;
const { axios } = require('../public/httpHelper');
const qs = require('qs');
const configDefault = require('../../config/config.default')();
class MandateService extends Service {
  async send(params) {
    const result = {
      msg: '',
      flag: false,
    };
    return new Promise(async (resolve, reject) => {
      // 调用site_server
      try {
        const mac = await macaddress.one();
        const mutation = gql `mutation Authorize_create($params:AuthorizeInput){
                    Authorize_create(params:$params)
                    }`;
        const variables = {
          params: {
            name: params.name,
            email: params.email,
            companyURL: '',
            telephone: params.telephone,
            address: params.address,
            users: parseInt(params.users),
            period: parseInt(params.period),
            unit: params.unit,
            random: params.random,
            mac,
          },
        };
        const res = await common.mutate(mutation, variables);
        const resObj = JSON.parse(res.data.Authorize_create);
        resolve(resObj);
      } catch (error) {
        result.msg = 'send fail,' + error;
        result.flag = false;
        reject(result);
      }
    });
  }
  async get(authorizeRequestId) {
    return new Promise(async (resolve, reject) => {
      try {
        if (!authorizeRequestId) {
          return resolve('tenant not exist');
        }
        const query = gql `query AuthorizeCode($id:String){
          AuthorizeCode(id:$id)
        }`;
        const variables = {
          id: authorizeRequestId,
        };
        const result = await common.query(query, variables);
        resolve(result.data.AuthorizeCode);
      } catch (error) {
        reject(error);
      }
    });
  }
  async checkCode(params) {
    const n = Buffer.from(params.name).toString('base64');
    const e = Buffer.from(params.email).toString('base64');
    const c = Buffer.from(params.companyURL).toString('base64');
    const t = Buffer.from(params.telephone).toString('base64');
    const a = Buffer.from(params.address).toString('base64');
    const u = Buffer.from(params.users).toString('base64');
    const period_base = Buffer.from(params.period).toString('base64');
    const unit_base = Buffer.from(params.unit).toString('base64');
    const mac = await macaddress.one();
    const userInfo = {
      name: n,
      email: e,
      company: c,
      telephone: t,
      address: a,
      users: u,
      period: period_base,
      unit: unit_base,
      random: params.random,
      mac,
    };
    const userLicense = {
      info: userInfo,
      prodCode: 'tbit',
    };
    const license = licenseKey.createLicense(userLicense);
    return license.license === params.code;
  }
  async check(params) {
    // 发送请求到site，确认验证码是否被使用过
    const query = gql `query AuthorizeState($authorizeCode:String){
            AuthorizeState(authorizeCode:$authorizeCode)
        }`;
    const variables = {
      authorizeCode: params.code,
    };
    const result = await common.query(query, variables);
    const json = JSON.parse(result.data.AuthorizeState);
    return json.status === 200;
  }
  async updateTenant(params, tenant) {
    const d = Date.now();
    let startTime,
      endTime;
    if (tenant && tenant.authorizedEndTime > d) {
      startTime = tenant.authorizedStartTime;
      endTime = moment(tenant.authorizedEndTime).add(params.period, params.unit === 'Day' ? 'days' : 'months').format('YYYY-MM-DD');
    } else {
      startTime = moment().format('YYYY-MM-DD');
      endTime = moment().add(params.period, params.unit === 'Day' ? 'days' : 'months').format('YYYY-MM-DD');
    }
    // 发送请求到site，通知已经验证生效
    const SetAuthorizeState = gql `mutation SetAuthorizeState($authorizeCode:String){
                SetAuthorizeState(authorizeCode:$authorizeCode)
            }`;
    const variables = {
      authorizeCode: params.code,
    };
    const res = await common.mutate(SetAuthorizeState, variables);
    console.log(res);
    // const jsonObj = JSON.parse(res.data.SetAuthorizeState);
    const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/updateTenantAuthroizeInfo`,
      data: qs.stringify({
        state: true,
        code: params.code,
        authorizedStartTime: startTime,
        authorizedEndTime: endTime,
        tenantid: params.tenantid,
      }),
    };
    await axios(config);
  }
  async singleMandate() {
    return await this.ctx.model.UserAdmin.findOne({
      where: { id: this.ctx.session.admin.id },
      include: [{
        model: this.ctx.model.TenantAdmin,
      }],
    });
  }
}

module.exports = MandateService;
